package com.ptone.messageCenter.common.utils;

import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

//import java.net.MalformedURLException;

@Component
public class APIRequest {

    public static String request(String url, String json) {
        String result = "";
        try {

            URL targetUrl = new URL(url);

            HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
            httpConnection.setDoOutput(true);
            httpConnection.setRequestMethod("POST");
            httpConnection.setRequestProperty("Content-Type", "application/json");
            httpConnection.setRequestProperty("Charset", "utf-8");

            OutputStream outputStream = httpConnection.getOutputStream();
            outputStream.write(json.getBytes("utf-8"));
            outputStream.flush();

            if (httpConnection.getResponseCode() != 200) {
                String msg = httpConnection.getResponseCode() + "--" + httpConnection.getResponseMessage() + "---" + httpConnection.getContentType();
                throw new RuntimeException(msg);
            }

            BufferedReader responseBuffer = new BufferedReader(new InputStreamReader((httpConnection.getInputStream()), "utf-8"));

            String output;
            while ((output = responseBuffer.readLine()) != null) {
                result = result + output;
            }

            httpConnection.disconnect();

        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }
        return result;
    }


}
